package com.sy.demo.dom4j;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

/**
 * 
 * Description: 该类演示了使用递归算法利用Dom4j取得一个文件夹的层次结构,并生成xml字符串. 
 * Copyright (c) Department of Research and Development/Beijing/W-Ya.
 * All Rights Reserved.
 * @version 1.0  Jun 19, 2010 6:17:31 PM  by 孙玮男（lukesun89@gmail.com）创建
 */
public class Dom4jDemo {

	public Dom4jDemo() {
	}

	public Document buildXML(String path) throws DocumentException {
		// 创建跟节点
		Document doc = DocumentHelper.parseText("<root></root>");
		Element ele = buildNode(doc.getRootElement(), path);
		doc.getRootElement().appendAttributes(ele);
		return doc;
	}

	public Element buildNode(Element ele, String path) {
		File file = new File(path);
		Element folder = ele.addElement("item");
		folder.addAttribute("name", file.getName());
		if (file.exists()) {
			File[] files = file.listFiles();
			if (files != null) {
				for (File child : files) {
					buildNode(folder, child.getPath());
				}
			}
		}
		return folder;
	}

	/**
	 * 递归生成xml形式目录结构
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Dom4jDemo dom = new Dom4jDemo();
		try {
			System.out.println(dom.buildXML("D:\\Root").asXML());
		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}
}